package com.leyou.user.web;

import com.leyou.auth.com.leyou.auth.utils.UserContext;
import com.leyou.auth.dto.UserDetails;
import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
@RequestMapping("info")
public class UserController {
    @Autowired
    UserService userService;


    //- 请求方式：GET
    //- 请求路径：/info/exists/{data}/{type}
    //- 请求参数：data,type
    //- 返回结果：true或false

    /**
     *  判读date是否存在
     * @param data  用户名或手机
     * @param type     数据类型1用户名 2手机
     * @return      是否可以使用
     */
    @GetMapping("exists/{data}/{type}")
    public ResponseEntity<Boolean> exists(@PathVariable("data") String data,
                                          @PathVariable("type") Integer type){
    return ResponseEntity.ok(userService.exists(data,type));
    }

    /**
     * 发送验证码
     * @param phone  发短信的目标手机号码
     * @return  无
     */
    @PostMapping("code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone){
            userService.sendCode(phone);
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 注册 我们在User参数后面跟一个BindingResult参数，不管校验是否通过，都会进入方法内部
     * @param user 用户属性
     * @param code 验证码
     * @return 无
     */
    @PostMapping
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
//         userService.register(user,code);
//         return ResponseEntity.status(HttpStatus.CREATED).build();

         //自定义返回结果
        if (result.hasErrors()) {
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400, msg);
        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    //根据用户名和密码查询用户
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByPhoneAndPassword(@RequestParam("username") String username,
                                                               @RequestParam("password") String password){
      return ResponseEntity.ok(userService.queryUserByPhoneAndPassword(username,password));
    }

    /**
     * 获取当前登录的用户信息 用来做用户登录回显
     * @return
     */
    @GetMapping("me")
    public ResponseEntity<UserDetails> me(){
        return ResponseEntity.ok(UserContext.getUser());
    }
}

